module.exports = app => {
    const express = require('express');
    
    const router = express.Router();
    const Waste = require('../model/wasteModel')
    
    const expressWs = require('express-ws')
    expressWs(router);

    // 添加废品
    router.post('/add',async (q,s)=>{
        let waste = await Waste.findOne({waste_name:q.body.waste_name});
        if(waste != null){
            s.send({
                data:"已有同名废品，请换个名字!",
                success:"false"
            })
            }else{
                let res = await Waste.create(q.body);
                s.send({
                    success:"true",
                    data:res
                });
            }
        })

    // 删除废品
    router.get('/delete/:id',async (q,s)=>{
        let waste = await Waste.findOne({_id:q.params.id});
        if(waste != null){
            await waste.remove();
            s.send({
                data:"",
                success:"true"
            })
            }else{
                s.send({
                    data:"找不到此废品!",
                    success:"false"
                })
            }
        })

    // 查找物品（模糊查询）
    router.get('/find/:waste_name',async (q,s)=>{
        let reg = new RegExp(q.params.waste_name,'g');
        let waste = await Waste.find({
            $or:[{waste_name:{$regex : reg}}]
        });
        s.send(waste);
        })


    router.get('/getAllWaste',async (q,s)=>{
        let waste = await Waste.find();
        s.send(waste);
        })

        // 修改物品信息
    router.post('/update/:id',async (q,s)=>{
        let waste = await Waste.findOne({_id:q.params.id});
        if(waste != null){
            waste.waste_url = q.body.waste_url == undefined ? waste.waste_url : q.body.waste_url;
            waste.species = q.body.species == undefined ? waste.species : q.body.species;
            waste.waste_name = q.body.waste_name == undefined ? waste.waste_name : q.body.waste_name;
            waste.price = q.body.price == undefined ? waste.price : q.body.price;
            waste.describe = q.body.describe == undefined ? waste.describe : q.body.describe;
            waste.compute_mode = q.body.compute_mode == undefined ? waste.compute_mode : q.body.compute_mode;
            waste.is_recycle = q.body.is_recycle == undefined ? waste.is_recycle : q.body.is_recycle;
            await waste.save();
            s.send({
                data:waste,
                success:"true"
            })
            }else{
                s.send({
                    data:"找不到此废品!",
                    success:"false"
                })
            }
        })

    // 批量修改物品信息
    router.post('/batchUpdate',async (q,s)=>{
        let waste = await Waste.find();
        waste.splice(0,waste.length,...q.body.waste);
        console.log(waste);
        Waste.updateMany();
        s.send(waste);
        })

    app.use('/waste',router);
}